﻿using System;
using System.IO;
using System.Drawing;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Drawing.Imaging;
namespace CommonLibraries.DeviceLibrary
{
    public static class ImageHelper
    {
        public static byte[] GetImageBytes(string FileName)
        {
            FileStream _FileStream = null;
            BinaryReader _BinaryReader = null;
            try
            {
                _FileStream = new FileStream(FileName, FileMode.Open);
                _BinaryReader = new BinaryReader(_FileStream);
                byte[] ImageBytes = _BinaryReader.ReadBytes((int)_FileStream.Length);
                return ImageBytes;

            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                _BinaryReader.Close();
                _FileStream.Close();
                _FileStream.Dispose();

            }
        }
        public static Image GetImage(byte[] ImageBytes)
        {
            MemoryStream _Ms = new MemoryStream(ImageBytes, 0, ImageBytes.Length);
            Bitmap _Photo;
            _Photo = new Bitmap(_Ms);
            _Ms.Close();
            _Ms.Dispose();
            return (Image)_Photo;
        }
        public static Image GetImage(string File)
        {
            Bitmap _Bmp = new Bitmap(File);
            return (Image)_Bmp;
        }
        public static List<string> FindImageByPosition(string PositionId, string ImagesFolder)
        {
            DirectoryInfo _Dir = null;
            FileInfo[] _Files = null;
            List<string> PathImages = new List<string>();
            _Dir = new DirectoryInfo(ImagesFolder);
            _Files = _Dir.GetFiles("*.jpeg");
            Regex _ValidarFileForPoint = new Regex("^" + PositionId + "_[0-9_]+4x.jpeg$");
            foreach (FileInfo _File in _Files)
            {
                if (_ValidarFileForPoint.Match(_File.Name).Success)
                    PathImages.Add(_File.FullName);
            }
            return PathImages;
        }
        public static bool DeleteImagesByPosition(string PositionId, string ImagesFolder)
        {
            try
            {
                List<string> FoundedImages = FindImageByPosition(PositionId, ImagesFolder);
                for (int i = 0; i < FoundedImages.Count; i++)
                {
                    File.Delete(FoundedImages[i]);
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        
        }
    }
}
